package br.ufpe.cin.quickmall.utils;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import br.ufpe.cin.quickmall.store.Offer;
import br.ufpe.cin.quickmall.store.Store;


public class JsonParser {
	
	public static final String ID_OFFER_JSON_TEXT = "id";
	public static final String STORE_OFFER_JSON_TEXT = "store";
	public static final String DESCRIPTION_OFFER_JSON_TEXT = "description";
	public static final String ACTIVE_OFFER_JSON_TEXT = "active";
	
	public static final String NAME_STORE_JSON_TEXT = "name";
	
	public static List<Offer> parseJsonTextToOfferList (String jsonText) throws JSONException {
		ArrayList<Offer> offerList = new ArrayList<Offer>();

		JSONArray jsonOfferList = new JSONArray(jsonText);
		
		for (int i = 0; i < jsonOfferList.length(); i++) {
			JSONObject jsonOffer = jsonOfferList.getJSONObject(i);
			offerList.add(JsonParser.parseJSONObjectToOffer(jsonOffer));
		}
		
		return offerList;
	}
	
	public static Offer parseJSONObjectToOffer(JSONObject jsonOffer) throws JSONException {
		Offer offer = new Offer();
		
		offer.setId(jsonOffer.getInt(ID_OFFER_JSON_TEXT));
		offer.setDescription(jsonOffer.getString(DESCRIPTION_OFFER_JSON_TEXT));
		offer.setActive(jsonOffer.getBoolean(ACTIVE_OFFER_JSON_TEXT));
		
		JSONObject jsonStore = jsonOffer.getJSONObject(STORE_OFFER_JSON_TEXT);
		String storeName = jsonStore.getString(NAME_STORE_JSON_TEXT);
		offer.setStore(new Store(storeName));
		
		return offer;
	}

}
